package com.hxgis.statisticanalysis.intelligentIndicator.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hxgis.export.DocxResolver;
import com.hxgis.export.ExpressionResolver;
import com.hxgis.statisticanalysis.intelligentIndicator.dao.jpa.MonthReportJpa;
import com.hxgis.statisticanalysis.intelligentIndicator.enums.FourLevelCode;
import com.hxgis.statisticanalysis.intelligentIndicator.enums.MonthReportType;
import com.hxgis.statisticanalysis.intelligentIndicator.pojo.MonthReport;
import com.hxgis.statisticanalysis.intelligentIndicator.vo.BusinessSystemStatistic;
import com.hxgis.statisticanalysis.intelligentIndicator.vo.monthreport.*;
import com.hxgis.statisticanalysis.utils.ExportUtil;
import com.hxgis.statisticanalysis.utils.TableMergeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.xmlbeans.XmlException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 赵恒
 * @date 2023/1/4
 */
@Service
@Slf4j
public class MonthReportService {
    @Resource
    private MonthReportJpa monthReportJpa;

    public Map<String, Object> queryAll(String month) {
        Map<String, Object> map = new HashMap<>();
        // 遍历枚举类MonthReportType
        for (MonthReportType type : MonthReportType.values()) {
            // 查询每个表的数据
            Object obj = null;
            if (type.isMonth()) {
                obj = query(month, type.toString());
            } else {
                obj = query("NONE", type.toString());
            }
            map.put(type.toString(), obj);
        }

        // 对于 国内气象通信系统本月新增数据量统计 表，不能为空
        if (map.get("NATIONAL_METEO_COMMUNICATION_SYSTEM_MONTH_ADD_DATA_STATISTIC") == null) {
            // 强制性塞入空数据
            List<RtCtsStationDiVO> stationDiVOList = new ArrayList<>();
            // 构建每一个四级编码的查询对象
            for (FourLevelCode value : FourLevelCode.values()) {

                RtCtsStationDiVO rtCtsStationDiVO = new RtCtsStationDiVO();
                rtCtsStationDiVO.setName(value.getName());
                rtCtsStationDiVO.setValue(0d);
                stationDiVOList.add(rtCtsStationDiVO);
            }
            RtCtsStationDiVO rtCtsStationDiVO = new RtCtsStationDiVO();
            rtCtsStationDiVO.setName("总计");
            double aDouble = stationDiVOList.stream().mapToDouble(RtCtsStationDiVO::getValue).sum();
            rtCtsStationDiVO.setValue(NumberUtil.round(aDouble, 2).doubleValue());
            stationDiVOList.add(rtCtsStationDiVO);
            map.put("NATIONAL_METEO_COMMUNICATION_SYSTEM_MONTH_ADD_DATA_STATISTIC", stationDiVOList);
        }

        // 按照前端的要求，要调整 本月气象云计算和存储资源分配情况 表的返回格式为List
        Object o1 = map.get("MONTH_METEO_CLOUD_CALC_AND_STORAGE_RESOURCE_DISTRIBUTION");
        if (o1 != null) {
            MonthMeteoCloud monthMeteoCloud = JSONUtil.toBean((JSONObject) o1, MonthMeteoCloud.class);
            // CPU资源
            MonthMeteoCloudVO monthMeteoCloudVO1 = new MonthMeteoCloudVO();
            monthMeteoCloudVO1.setPhysicalMachineCount(monthMeteoCloud.getPhysicalMachineCount());
            monthMeteoCloudVO1.setVirtualMachineCount(monthMeteoCloud.getVirtualMachineCount());
            monthMeteoCloudVO1.setIntensiveRatio(monthMeteoCloud.getIntensiveRatio());
            monthMeteoCloudVO1.setResource("CPU（核）");
            // CPU的值不保留小数
            double cpuTotal = NumberUtil.round(monthMeteoCloud.getCpuTotal(), 0).doubleValue();
            monthMeteoCloudVO1.setTotal(cpuTotal);
            double cpuDistributed = NumberUtil.round(monthMeteoCloud.getCpuDistributed(), 0).doubleValue();
            monthMeteoCloudVO1.setDistributed(cpuDistributed);
            monthMeteoCloudVO1.setDistributedRatio(monthMeteoCloud.getCpuDistributeRatio());
            // 内存资源
            MonthMeteoCloudVO monthMeteoCloudVO2 = new MonthMeteoCloudVO();
            monthMeteoCloudVO2.setPhysicalMachineCount(monthMeteoCloud.getPhysicalMachineCount());
            monthMeteoCloudVO2.setVirtualMachineCount(monthMeteoCloud.getVirtualMachineCount());
            monthMeteoCloudVO2.setIntensiveRatio(monthMeteoCloud.getIntensiveRatio());
            monthMeteoCloudVO2.setResource("内存（TB）");
            monthMeteoCloudVO2.setTotal(monthMeteoCloud.getMemoryTotal());
            monthMeteoCloudVO2.setDistributed(monthMeteoCloud.getMemoryDistributed());
            monthMeteoCloudVO2.setDistributedRatio(monthMeteoCloud.getMemoryDistributedRatio());
            // 本地存储
            MonthMeteoCloudVO monthMeteoCloudVO3 = new MonthMeteoCloudVO();
            monthMeteoCloudVO3.setPhysicalMachineCount(monthMeteoCloud.getPhysicalMachineCount());
            monthMeteoCloudVO3.setVirtualMachineCount(monthMeteoCloud.getVirtualMachineCount());
            monthMeteoCloudVO3.setIntensiveRatio(monthMeteoCloud.getIntensiveRatio());
            monthMeteoCloudVO3.setResource("本地存储（TB）");
            monthMeteoCloudVO3.setTotal(monthMeteoCloud.getLocalStorageTotal());
            monthMeteoCloudVO3.setDistributed(monthMeteoCloud.getLocalStorageDistributed());
            monthMeteoCloudVO3.setDistributedRatio(monthMeteoCloud.getLocalStorageDistributeRatio());
            // 网络存储
            MonthMeteoCloudVO monthMeteoCloudVO4 = new MonthMeteoCloudVO();
            monthMeteoCloudVO4.setPhysicalMachineCount(monthMeteoCloud.getPhysicalMachineCount());
            monthMeteoCloudVO4.setVirtualMachineCount(monthMeteoCloud.getVirtualMachineCount());
            monthMeteoCloudVO4.setIntensiveRatio(monthMeteoCloud.getIntensiveRatio());
            monthMeteoCloudVO4.setResource("网络存储（TB）");
            monthMeteoCloudVO4.setTotal(monthMeteoCloud.getNetStorageTotal());
            monthMeteoCloudVO4.setDistributed(monthMeteoCloud.getNetStorageDistributed());
            monthMeteoCloudVO4.setDistributedRatio(monthMeteoCloud.getNetStorageDistributeRatio());

            List<MonthMeteoCloudVO> monthMeteoCloudVOList = new ArrayList<>();
            monthMeteoCloudVOList.add(monthMeteoCloudVO1);
            monthMeteoCloudVOList.add(monthMeteoCloudVO2);
            monthMeteoCloudVOList.add(monthMeteoCloudVO3);
            monthMeteoCloudVOList.add(monthMeteoCloudVO4);

            map.put("MONTH_METEO_CLOUD_CALC_AND_STORAGE_RESOURCE_DISTRIBUTION", monthMeteoCloudVOList);
        }

        // 适配 本月通信网络总体运行情况 表到前端
        Object o2 = map.get("MONTH_COMMUNICATION_NET_TOTAL_RUNNING");
        if (o2 != null) {
            MonthCommunicationNet monthCommunicationNet = JSONUtil.toBean((JSONObject) o2, MonthCommunicationNet.class);
            MonthCommunicationNetVO monthCommunicationNetVO1 = new MonthCommunicationNetVO();
            monthCommunicationNetVO1.setStatusName("故障次数");
            monthCommunicationNetVO1.setIntranetNetArea(monthCommunicationNet.getIntranetNetAreaFailureCount());
            monthCommunicationNetVO1.setIntranetExternalLine(monthCommunicationNet.getIntranetExternalLineFailureCount());
            monthCommunicationNetVO1.setExtranetNetArea(monthCommunicationNet.getExtranetNetAreaFailureCount());
            monthCommunicationNetVO1.setExtranetExternalLine(monthCommunicationNet.getExtranetExternalLineFailureCount());
            monthCommunicationNetVO1.setSafetyEvent(monthCommunicationNet.getSafetyEventFailureCount());

            MonthCommunicationNetVO monthCommunicationNetVO2 = new MonthCommunicationNetVO();
            monthCommunicationNetVO2.setStatusName("处理情况");
            monthCommunicationNetVO2.setIntranetNetArea(monthCommunicationNet.getIntranetNetAreaDealStatus());
            monthCommunicationNetVO2.setIntranetExternalLine(monthCommunicationNet.getIntranetExternalLineDealStatus());
            monthCommunicationNetVO2.setExtranetNetArea(monthCommunicationNet.getExtranetNetAreaDealStatus());
            monthCommunicationNetVO2.setExtranetExternalLine(monthCommunicationNet.getExtranetExternalLineDealStatus());
            monthCommunicationNetVO2.setSafetyEvent(monthCommunicationNet.getSafetyEventDealStatus());

            MonthCommunicationNetVO monthCommunicationNetVO3 = new MonthCommunicationNetVO();
            monthCommunicationNetVO3.setStatusName("恢复情况");
            monthCommunicationNetVO3.setIntranetNetArea(monthCommunicationNet.getIntranetNetAreaRecoverStatus());
            monthCommunicationNetVO3.setIntranetExternalLine(monthCommunicationNet.getIntranetExternalLineRecoverStatus());
            monthCommunicationNetVO3.setExtranetNetArea(monthCommunicationNet.getExtranetNetAreaRecoverStatus());
            monthCommunicationNetVO3.setExtranetExternalLine(monthCommunicationNet.getExtranetExternalLineRecoverStatus());
            monthCommunicationNetVO3.setSafetyEvent(monthCommunicationNet.getSafetyEventRecoverStatus());

            List<MonthCommunicationNetVO> monthCommunicationNetVOList = new ArrayList<>();
            monthCommunicationNetVOList.add(monthCommunicationNetVO1);
            monthCommunicationNetVOList.add(monthCommunicationNetVO2);
            monthCommunicationNetVOList.add(monthCommunicationNetVO3);
            map.put("MONTH_COMMUNICATION_NET_TOTAL_RUNNING", monthCommunicationNetVOList);
        }

        return map;
    }

    public int updateAll(Map<String, Object> allData) {
        int i = 0;
        String month = allData.get("month").toString();

        // 将对象转化为json字符串时用得到
        JSONConfig jsonConfig = new JSONConfig();
        jsonConfig.setIgnoreNullValue(false);

        for (String key : allData.keySet()) {
            MonthReportType monthReportType = getMonthReportType(key);
            // 如果是误传的键，则跳过
            if (monthReportType == null) {
                continue;
            }
            // 获取数据内容
            Object o = allData.get(key);
            String content = "";
            if (o == null) {
                content = null;
            } else {
                content = JSONUtil.toJsonStr(o);
            }
            // 处理带有总计或比例等需要计算的数据
            // “天镜”对接业务系统监视情况概览
            if (key.equals("TIANJING_JOINT_BUSINESS_SYSTEM_OVERVIEW")) {
                TianjingJoinOverview tianjingJoinOverview = JSONUtil.toBean(content, TianjingJoinOverview.class);
                tianjingJoinOverview.setJoinTotal(tianjingJoinOverview.getJoined() + tianjingJoinOverview.getJoining());
                content = JSONUtil.toJsonStr(tianjingJoinOverview);
            }
            // 国内气象通信系统本月新增数据量统计
            if (key.equals("NATIONAL_METEO_COMMUNICATION_SYSTEM_MONTH_ADD_DATA_STATISTIC")) {
                List<RtCtsStationDiVO> rtCtsStationDiVOList = JSONUtil.toList(content, RtCtsStationDiVO.class);
                // 计算总和
                double sum = rtCtsStationDiVOList.stream()
                        .filter(rtCtsStationDiVO -> !rtCtsStationDiVO.getName().equals("总计"))
                        .mapToDouble(RtCtsStationDiVO::getValue)
                        .sum();

                // 判断是否有 总计 对象
                Optional<RtCtsStationDiVO> optional = rtCtsStationDiVOList.stream()
                        .filter(rtCtsStationDiVO -> rtCtsStationDiVO.getName().equals("总计"))
                        .findAny();
                // 如果不存在总计，新建对象，有则不管
                if (!optional.isPresent()) {
                    RtCtsStationDiVO rtCtsStationDiVO = new RtCtsStationDiVO();
                    rtCtsStationDiVO.setName("总计");
                    rtCtsStationDiVOList.add(rtCtsStationDiVO);
                }

                for (RtCtsStationDiVO rtCtsStationDiVO : rtCtsStationDiVOList) {
                    if (rtCtsStationDiVO.getName().equals("总计")) {
                        // 保留两位
                        rtCtsStationDiVO.setValue(NumberUtil.round(sum, 2).doubleValue());
                        break;
                    }
                }
                content = JSONUtil.toJsonStr(rtCtsStationDiVOList);
            }

            // 本月天擎服务接口数据资源使用情况
            if (key.equals("MONTH_TIANQING_SERVICE_INTERFACE_DATA_RESOURCE")) {
                List<DataResourceUse> dataResourceUseList = JSONUtil.toList(content, DataResourceUse.class);
                // 获取除合计之外的总量
                double sumDataSize = dataResourceUseList.stream().filter(dataResourceUse -> !dataResourceUse.getDataClassName().equals("合计")).mapToDouble(DataResourceUse::getDataSize).sum();
                int sumQueryTimes = dataResourceUseList.stream().filter(dataResourceUse -> !dataResourceUse.getDataClassName().equals("合计")).mapToInt(DataResourceUse::getQueryTimes).sum();
                // 判断集合中是否含有合计
                Optional<DataResourceUse> optional = dataResourceUseList.stream().filter(dataResourceUse -> dataResourceUse.getDataClassName().equals("合计")).findAny();
                if (!optional.isPresent()) {
                    DataResourceUse dataResourceUse = new DataResourceUse();
                    dataResourceUse.setDataClassName("合计");
                    dataResourceUseList.add(dataResourceUse);
                }
                for (DataResourceUse dataResourceUse : dataResourceUseList) {
                    if (dataResourceUse.getDataClassName().equals("合计")) {
                        dataResourceUse.setDataSize(sumDataSize);
                        dataResourceUse.setQueryTimes(sumQueryTimes);
                    }
                }
                content = JSONUtil.toJsonStr(dataResourceUseList);
            }

            // 各单位业务系统及算法融入省级“天擎”情况总览
            if (key.equals("UNIT_BUSINESS_SYSTEM_AND_ALGORITHM_IN_TIANQING")) {
                List<BusinessSystemNumberVO> businessSystemNumberVOList = JSONUtil.toList(content, BusinessSystemNumberVO.class);
                int algorithmCountSum = businessSystemNumberVOList.stream().filter(businessSystemNumberVO -> !businessSystemNumberVO.getBusinessUnit().equals("总计"))
                        .mapToInt(BusinessSystemNumberVO::getAlgorithmCount).sum();
                int productCountSum = businessSystemNumberVOList.stream().filter(businessSystemNumberVO -> !businessSystemNumberVO.getBusinessUnit().equals("总计"))
                        .mapToInt(BusinessSystemNumberVO::getProductCount).sum();
                int businessSystemCountSum = businessSystemNumberVOList.stream().filter(businessSystemNumberVO -> !businessSystemNumberVO.getBusinessUnit().equals("总计"))
                        .mapToInt(BusinessSystemNumberVO::getBusinessSystemCount).sum();
                Optional<BusinessSystemNumberVO> optional = businessSystemNumberVOList.stream().filter(businessSystemNumberVO -> businessSystemNumberVO.getBusinessUnit().equals("总计")).findAny();
                if (!optional.isPresent()) {
                    BusinessSystemNumberVO businessSystemNumberVO = new BusinessSystemNumberVO();
                    businessSystemNumberVO.setBusinessUnit("总计");
                }
                for (BusinessSystemNumberVO businessSystemNumberVO : businessSystemNumberVOList) {
                    if (businessSystemNumberVO.getBusinessUnit().equals("总计")) {
                        businessSystemNumberVO.setBusinessSystemCount(businessSystemCountSum);
                        businessSystemNumberVO.setAlgorithmCount(algorithmCountSum);
                        businessSystemNumberVO.setProductCount(productCountSum);
                    }
                }
            }

            // 本月业务系统运行情况统计
            if (key.equals("MONTH_BUSINESS_SYSTEM_RUNNING_STATISTIC")) {
                // 对type为2的行设定百分比
                List<MonthBusinessSystemRunning> systemRunningList = JSONUtil.toList(content, MonthBusinessSystemRunning.class);
                // 用新的来添加
                List<MonthBusinessSystemRunning> systemRunningList1 = new ArrayList<>();
                // 按照业务系统名称分组
                Map<String, List<MonthBusinessSystemRunning>> listMap = systemRunningList.stream()
                        .filter(monthBusinessSystemRunning -> StrUtil.isNotEmpty(monthBusinessSystemRunning.getType()))
                        .filter(monthBusinessSystemRunning -> StrUtil.isNotEmpty(monthBusinessSystemRunning.getBusinessSystemName()))
                        .collect(Collectors.groupingBy(MonthBusinessSystemRunning::getBusinessSystemName));
                int seriousAlarmDealtSum = 0;
                int seriousAlarmFollowSum = 0;
                int seriousAlarmTotalSum = 0;
                int keyAlarmDealtSum = 0;
                int keyAlarmFollowSum = 0;
                int keyAlarmTotalSum = 0;
                for (String name : listMap.keySet()) {
                    // 修改type为2的数据
                    List<MonthBusinessSystemRunning> systemRunnings = listMap.get(name);
                    // 分别获取type=1和type=2的对象
                    Optional<MonthBusinessSystemRunning> optional1 = systemRunnings.stream().filter(monthBusinessSystemRunning -> monthBusinessSystemRunning.getType().equals("1")).findAny();
                    Optional<MonthBusinessSystemRunning> optional2 = systemRunnings.stream().filter(monthBusinessSystemRunning -> monthBusinessSystemRunning.getType().equals("2")).findAny();
                    if (!optional1.isPresent() || !optional2.isPresent()) {
                        continue;
                    }
                    MonthBusinessSystemRunning systemRunning1 = optional1.get();
                    MonthBusinessSystemRunning systemRunning2 =optional2.get();




                    int seriousAlarmDealt = Integer.parseInt(systemRunning1.getSeriousAlarmDealt());
                    int seriousAlarmFollow = Integer.parseInt(systemRunning1.getSeriousAlarmFollow());
                    int seriousAlarmTotal = seriousAlarmDealt + seriousAlarmFollow;

                    int keyAlarmDealt = Integer.parseInt(systemRunning1.getKeyAlarmDealt());
                    int keyAlarmFollow = Integer.parseInt(systemRunning1.getKeyAlarmFollow());
                    int keyAlarmTotal = keyAlarmDealt + keyAlarmFollow;

                    // 顺便计算总和
                    seriousAlarmDealtSum += seriousAlarmDealt;
                    seriousAlarmFollowSum += seriousAlarmFollow;
                    seriousAlarmTotalSum += seriousAlarmTotal;
                    keyAlarmDealtSum += keyAlarmDealt;
                    keyAlarmFollowSum += keyAlarmFollow;
                    keyAlarmTotalSum += keyAlarmTotal;

                    // 设置第一个对象的总量
                    systemRunning1.setSeriousAlarmTotal(String.valueOf(seriousAlarmTotal));
                    systemRunning1.setKeyAlarmTotal(String.valueOf(keyAlarmTotal));

                    // 设置第二个对象的值
                    if (seriousAlarmTotal == 0) {
                        systemRunning2.setSeriousAlarmTotal("0%");
                        systemRunning2.setSeriousAlarmDealt("0%");
                        systemRunning2.setSeriousAlarmFollow("0%");
                    } else {
                        systemRunning2.setSeriousAlarmTotal("100%");
                        systemRunning2.setSeriousAlarmDealt(NumberUtil.decimalFormat("#.##%", seriousAlarmDealt * 1.0 / seriousAlarmTotal));
                        systemRunning2.setSeriousAlarmFollow(NumberUtil.decimalFormat("#.##%", seriousAlarmFollow * 1.0 / seriousAlarmTotal));
                    }

                    if (keyAlarmTotal == 0) {
                        systemRunning2.setKeyAlarmTotal("0%");
                        systemRunning2.setKeyAlarmDealt("0%");
                        systemRunning2.setKeyAlarmFollow("0%");
                    } else {
                        systemRunning2.setKeyAlarmTotal("100%");
                        systemRunning2.setKeyAlarmDealt(NumberUtil.decimalFormat("#.##%", keyAlarmDealt * 1.0 / keyAlarmTotal));
                        systemRunning2.setKeyAlarmFollow(NumberUtil.decimalFormat("#.##%", keyAlarmFollow * 1.0 / keyAlarmTotal));
                    }
                    systemRunningList1.add(systemRunning1);
                    systemRunningList1.add(systemRunning2);
                }
                // 建立总计的对象
                MonthBusinessSystemRunning sumSystemRunning = new MonthBusinessSystemRunning();
                sumSystemRunning.setBusinessSystemName("总计（条）");
                sumSystemRunning.setSeriousAlarmTotal(String.valueOf(seriousAlarmTotalSum));
                sumSystemRunning.setSeriousAlarmDealt(String.valueOf(seriousAlarmDealtSum));
                sumSystemRunning.setSeriousAlarmFollow(String.valueOf(seriousAlarmFollowSum));
                sumSystemRunning.setKeyAlarmTotal(String.valueOf(keyAlarmTotalSum));
                sumSystemRunning.setKeyAlarmDealt(String.valueOf(keyAlarmDealtSum));
                sumSystemRunning.setKeyAlarmFollow(String.valueOf(keyAlarmFollowSum));

                systemRunningList1.add(sumSystemRunning);
                content = JSONUtil.toJsonStr(systemRunningList1);
            }

            // 特殊处理 MONTH_METEO_CLOUD_CALC_AND_STORAGE_RESOURCE_DISTRIBUTION 和 MONTH_COMMUNICATION_NET_TOTAL_RUNNING
            // 本月气象云计算和存储资源分配情况
            if (key.equals("MONTH_METEO_CLOUD_CALC_AND_STORAGE_RESOURCE_DISTRIBUTION")) {
                MonthMeteoCloud monthMeteoCloud = new MonthMeteoCloud();

                List<MonthMeteoCloudVO> monthMeteoCloudVOList = JSONUtil.toList(content, MonthMeteoCloudVO.class);
                for (MonthMeteoCloudVO monthMeteoCloudVO : monthMeteoCloudVOList) {
                    if (monthMeteoCloudVO.getResource().equals("CPU（核）")) {
                        int physicalMachineCount = monthMeteoCloudVO.getPhysicalMachineCount();
                        int virtualMachineCount = monthMeteoCloudVO.getVirtualMachineCount();
                        monthMeteoCloud.setPhysicalMachineCount(physicalMachineCount);
                        monthMeteoCloud.setVirtualMachineCount(virtualMachineCount);
                        // 计算集约比
                        if (physicalMachineCount != 0 && virtualMachineCount != 0) {
                            double intensiveRatio = virtualMachineCount * 1.0 / physicalMachineCount;
                            // 保留两位
                            String ratio = NumberUtil.decimalFormat("#.##", intensiveRatio);
                            monthMeteoCloud.setIntensiveRatio("1:" + ratio);
                        } else {
                            monthMeteoCloud.setIntensiveRatio("0");
                        }

                        monthMeteoCloud.setCpuTotal(monthMeteoCloudVO.getTotal());
                        monthMeteoCloud.setCpuDistributed(monthMeteoCloudVO.getDistributed());

                        // 计算分配率
                        if (monthMeteoCloud.getCpuTotal() != 0) {
                            double cpuRatio = monthMeteoCloud.getCpuDistributed() / monthMeteoCloud.getCpuTotal();
                            monthMeteoCloud.setCpuDistributeRatio(NumberUtil.decimalFormat("#.##%", cpuRatio));
                        } else {
                            monthMeteoCloud.setCpuDistributeRatio("0%");
                        }
                    } else if (monthMeteoCloudVO.getResource().equals("内存（TB）")) {
                        monthMeteoCloud.setMemoryTotal(monthMeteoCloudVO.getTotal());
                        monthMeteoCloud.setMemoryDistributed(monthMeteoCloudVO.getDistributed());

                        if (monthMeteoCloud.getMemoryTotal() != 0) {
                            double memoryRatio = monthMeteoCloud.getMemoryDistributed() / monthMeteoCloud.getMemoryTotal();
                            monthMeteoCloud.setMemoryDistributedRatio(NumberUtil.decimalFormat("#.##%", memoryRatio));
                        } else {
                            monthMeteoCloud.setMemoryDistributedRatio("0%");
                        }
                    } else if (monthMeteoCloudVO.getResource().equals("本地存储（TB）")) {
                        monthMeteoCloud.setLocalStorageTotal(monthMeteoCloudVO.getTotal());
                        monthMeteoCloud.setLocalStorageDistributed(monthMeteoCloudVO.getDistributed());

                        if (monthMeteoCloud.getLocalStorageTotal() != 0) {
                            double localStorageRatio = monthMeteoCloud.getLocalStorageDistributed() / monthMeteoCloud.getLocalStorageTotal();
                            monthMeteoCloud.setLocalStorageDistributeRatio(NumberUtil.decimalFormat("#.##%", localStorageRatio));
                        } else {
                            monthMeteoCloud.setLocalStorageDistributeRatio("0%");
                        }

                    } else if (monthMeteoCloudVO.getResource().equals("网络存储（TB）")) {
                        monthMeteoCloud.setNetStorageTotal(monthMeteoCloudVO.getTotal());
                        monthMeteoCloud.setNetStorageDistributed(monthMeteoCloudVO.getDistributed());

                        if (monthMeteoCloud.getNetStorageTotal() != 0) {
                            double netStorageRatio = monthMeteoCloud.getNetStorageDistributed() / monthMeteoCloud.getNetStorageTotal();
                            monthMeteoCloud.setNetStorageDistributeRatio(NumberUtil.decimalFormat("#.##%", netStorageRatio));
                        }

                        monthMeteoCloud.setNetStorageDistributeRatio(monthMeteoCloudVO.getDistributedRatio());
                    }
                }
                content = JSONUtil.toJsonStr(monthMeteoCloud, jsonConfig);
            }

            // 本月通信网络总体运行情况
            if (key.equals("MONTH_COMMUNICATION_NET_TOTAL_RUNNING")) {
                MonthCommunicationNet monthCommunicationNet = new MonthCommunicationNet();
                List<MonthCommunicationNetVO> monthCommunicationNetVOList = JSONUtil.toList(content, MonthCommunicationNetVO.class);
                for (MonthCommunicationNetVO monthCommunicationNetVO : monthCommunicationNetVOList) {
                    if (monthCommunicationNetVO.getStatusName().equals("故障次数")) {
                        monthCommunicationNet.setIntranetNetAreaFailureCount(monthCommunicationNetVO.getIntranetNetArea());
                        monthCommunicationNet.setIntranetExternalLineFailureCount(monthCommunicationNetVO.getIntranetExternalLine());
                        monthCommunicationNet.setExtranetNetAreaFailureCount(monthCommunicationNetVO.getExtranetNetArea());
                        monthCommunicationNet.setExtranetExternalLineFailureCount(monthCommunicationNetVO.getExtranetExternalLine());
                        monthCommunicationNet.setSafetyEventFailureCount(monthCommunicationNetVO.getSafetyEvent());
                    } else if (monthCommunicationNetVO.getStatusName().equals("处理情况")) {
                        monthCommunicationNet.setIntranetNetAreaDealStatus(monthCommunicationNetVO.getIntranetNetArea());
                        monthCommunicationNet.setIntranetExternalLineDealStatus(monthCommunicationNetVO.getIntranetExternalLine());
                        monthCommunicationNet.setExtranetNetAreaDealStatus(monthCommunicationNetVO.getExtranetNetArea());
                        monthCommunicationNet.setExtranetExternalLineDealStatus(monthCommunicationNetVO.getExtranetExternalLine());
                        monthCommunicationNet.setSafetyEventDealStatus(monthCommunicationNetVO.getSafetyEvent());

                    } else if (monthCommunicationNetVO.getStatusName().equals("恢复情况")) {
                        monthCommunicationNet.setIntranetNetAreaRecoverStatus(monthCommunicationNetVO.getIntranetNetArea());
                        monthCommunicationNet.setIntranetExternalLineRecoverStatus(monthCommunicationNetVO.getIntranetExternalLine());
                        monthCommunicationNet.setExtranetNetAreaRecoverStatus(monthCommunicationNetVO.getExtranetNetArea());
                        monthCommunicationNet.setExtranetExternalLineRecoverStatus(monthCommunicationNetVO.getExtranetExternalLine());
                        monthCommunicationNet.setSafetyEventRecoverStatus(monthCommunicationNetVO.getSafetyEvent());
                    }
                }
                content = JSONUtil.toJsonStr(monthCommunicationNet);
            }

            // 修改到数据库中
            MonthReport monthReport = new MonthReport();
            // 判断当前表格是否跟月份有关
            if (monthReportType.isMonth()) {
                monthReport.setMonth(month);
            } else {
                monthReport.setMonth("NONE");
            }
            monthReport.setName(key);
            monthReport.setTitle(monthReportType.getTitle());
            monthReport.setContent(content);
            i += saveOrUpdate(monthReport);
        }
        return i;
    }

    private MonthReportType getMonthReportType(String key) {
        MonthReportType monthReportType = null;
        for (MonthReportType reportType : MonthReportType.values()) {
            if (reportType.toString().equals(key)) {
                monthReportType = reportType;
            }
        }
        return monthReportType;
    }

    private boolean isMonthReportType(String key) {
        boolean b = false;
        for (MonthReportType reportType : MonthReportType.values()) {
            if (reportType.toString().equals(key)) {
                b = true;
                break;
            }
        }
        return b;
    }

    private boolean isMonth(String key) {
        boolean b = false;
        for (MonthReportType reportType : MonthReportType.values()) {
            if (reportType.toString().equals(key)) {
                b = reportType.isMonth();
                break;
            }
        }
        return b;
    }

    public Object query(String month, String name) {
        List<MonthReport> monthReportList = monthReportJpa.query(month, name);
        if (CollectionUtils.isEmpty(monthReportList)) {
            return null;
        } else {
            // 将空字符串、{}、[] 都返回 null
            String s = monthReportList.get(0).getContent();
            if (StrUtil.isEmpty(s) || "{}".equals(s) || "[]".equals(s)) {
                return null;
            } else if (StrUtil.startWith(s, "[")) {
                return JSONUtil.parseArray(s);
            } else if (StrUtil.startWith(s, "{")) {
                return JSONUtil.parseObj(s);
            } else {
                return s;
            }
        }
    }

    public int saveOrUpdate(MonthReport monthReport) {
        boolean b = exist(monthReport);
        if (b) {
            // 更新
            int i = monthReportJpa.updateByMonthAndName(monthReport.getMonth(), monthReport.getName(), monthReport.getContent());
        } else {
            // 保存
            monthReportJpa.save(monthReport);
        }
        return 1;
    }

    public boolean exist(MonthReport monthReport) {
        int i = monthReportJpa.findByMonthAndName(monthReport.getMonth(), monthReport.getName());
        return i > 0;
    }

    /**
     * 导出word文档
     * @param month 月份
     * @param response http返回对象
     */
    public void exportWord(String month, HttpServletResponse response) {
        MonthReportWordBean wordBean = new MonthReportWordBean();
        // 解析年月
        DateTime dateTime = DateUtil.parse(month, "yyyyMM");
        String yearStr = String.valueOf(dateTime.year());
        String monthStr = String.valueOf(dateTime.month() + 1);
        wordBean.setYear(yearStr);
        wordBean.setMonth(monthStr);
        // 从数据库读取对应的数据, map用来存放每个表格对应的数据，全部放在一起返回
        Map<String, Object> map = new HashMap<>();
        // 遍历枚举类MonthReportType
        for (MonthReportType type : MonthReportType.values()) {
            // 查询每个表的数据
            Object obj = null;
            if (type.isMonth()) {
                obj = query(month, type.toString());
            } else {
                obj = query("NONE", type.toString());
            }
            map.put(type.toString(), obj);
        }
        // 插入对应的数据
        // 2.1 “天镜”对接业务系统监视情况概览
        if (map.get("TIANJING_JOINT_BUSINESS_SYSTEM_OVERVIEW") == null) {
            wordBean.setVar2_1("0");
            wordBean.setVar2_2("0");
            wordBean.setVar2_3("0");
        } else {
            TianjingJoinOverview tianjingJoinOverview = JSONUtil.toBean(map.get("TIANJING_JOINT_BUSINESS_SYSTEM_OVERVIEW").toString(), TianjingJoinOverview.class);
            if (tianjingJoinOverview == null) {
                wordBean.setVar2_1("0");
                wordBean.setVar2_2("0");
                wordBean.setVar2_3("0");
            } else {
                wordBean.setVar2_1(String.valueOf(tianjingJoinOverview.getJoined()));
                wordBean.setVar2_2(String.valueOf(tianjingJoinOverview.getJoining()));
                wordBean.setVar2_3(String.valueOf(tianjingJoinOverview.getJoinTotal()));
            }
        }

        // 3.1 国内气象通信系统本月新增数据量统计
        if (map.get("NATIONAL_METEO_COMMUNICATION_SYSTEM_MONTH_ADD_DATA_STATISTIC") == null) {
            wordBean.setVar3_1("0");
            wordBean.setVar3_2("0");
            wordBean.setVar3_3("0");
            wordBean.setVar3_4("0");
            wordBean.setVar3_5("0");
            wordBean.setVar3_6("0");
            wordBean.setVar3_7("0");
        } else {
            List<RtCtsStationDiVO> rtCtsStationDiVOList = JSONUtil.toList(map.get("NATIONAL_METEO_COMMUNICATION_SYSTEM_MONTH_ADD_DATA_STATISTIC").toString(), RtCtsStationDiVO.class);
            for (RtCtsStationDiVO rtCtsStationDiVO : rtCtsStationDiVOList) {
                String name = rtCtsStationDiVO.getName();
                String value = rtCtsStationDiVO.getValue() == 0 ? "0" :String.valueOf(rtCtsStationDiVO.getValue());
                if (FourLevelCode.A.getName().equals(name)) {
                    wordBean.setVar3_1(value);
                } else if (FourLevelCode.B.getName().equals(name)) {
                    wordBean.setVar3_2(value);
                }else if (FourLevelCode.J.getName().equals(name)) {
                    wordBean.setVar3_3(value);
                }else if (FourLevelCode.K.getName().equals(name)) {
                    wordBean.setVar3_4(value);
                }else if (FourLevelCode.F.getName().equals(name)) {
                    wordBean.setVar3_5(value);
                }else if (FourLevelCode.M.getName().equals(name)) {
                    wordBean.setVar3_6(value);
                } else if ("总计".equals(name)) {
                    wordBean.setVar3_7(value);
                }
            }
        }
        wordBean.setVar3_8(yearStr);
        wordBean.setVar3_9(monthStr);

        // 6.1 气象云资源池总览
        if (map.get("METEO_CLOUD_RESOURCE_POOL_OVERVIEW") == null) {
            wordBean.setVar6_1("0");
            wordBean.setVar6_2("0");
            wordBean.setVar6_3("0");
        } else {
            MeteoCloudOverview meteoCloudOverview = JSONUtil.toBean(map.get("METEO_CLOUD_RESOURCE_POOL_OVERVIEW").toString(), MeteoCloudOverview.class);
            wordBean.setVar6_1(String.valueOf(meteoCloudOverview.getPhysicServerCount()));
            wordBean.setVar6_2(String.valueOf(meteoCloudOverview.getLocalStorageCount()));
            wordBean.setVar6_3(String.valueOf(meteoCloudOverview.getNetStorageCount()));
        }

        // 6.2 本月气象云计算和存储资源分配情况
        if (map.get("MONTH_METEO_CLOUD_CALC_AND_STORAGE_RESOURCE_DISTRIBUTION") == null) {
            wordBean.setVar6_4("0");
            wordBean.setVar6_5("0");
            wordBean.setVar6_6("0");
            wordBean.setVar6_7("0");
            wordBean.setVar6_8("0");
            wordBean.setVar6_9("0");
            wordBean.setVar6_10("0");
            wordBean.setVar6_11("0");
            wordBean.setVar6_12("0");
            wordBean.setVar6_13("0");
            wordBean.setVar6_14("0");
            wordBean.setVar6_15("0");
            wordBean.setVar6_16("0");
            wordBean.setVar6_17("0");
            wordBean.setVar6_18("0");
        } else {
            MonthMeteoCloud monthMeteoCloud = JSONUtil.toBean(map.get("MONTH_METEO_CLOUD_CALC_AND_STORAGE_RESOURCE_DISTRIBUTION").toString(), MonthMeteoCloud.class);
            if (monthMeteoCloud == null) {
                wordBean.setVar6_4("0");
                wordBean.setVar6_5("0");
                wordBean.setVar6_6("0");
                wordBean.setVar6_7("0");
                wordBean.setVar6_8("0");
                wordBean.setVar6_9("0");
                wordBean.setVar6_10("0");
                wordBean.setVar6_11("0");
                wordBean.setVar6_12("0");
                wordBean.setVar6_13("0");
                wordBean.setVar6_14("0");
                wordBean.setVar6_15("0");
                wordBean.setVar6_16("0");
                wordBean.setVar6_17("0");
                wordBean.setVar6_18("0");
            } else {
                wordBean.setVar6_4(String.valueOf(monthMeteoCloud.getPhysicalMachineCount()));
                wordBean.setVar6_5(String.valueOf(monthMeteoCloud.getVirtualMachineCount()));
                wordBean.setVar6_6(monthMeteoCloud.getIntensiveRatio());
                wordBean.setVar6_7(NumberUtil.decimalFormat("#", monthMeteoCloud.getCpuTotal()));
                wordBean.setVar6_8(NumberUtil.decimalFormat("#", monthMeteoCloud.getCpuDistributed()));
                wordBean.setVar6_9(monthMeteoCloud.getCpuDistributeRatio());
                wordBean.setVar6_10(String.valueOf(monthMeteoCloud.getMemoryTotal()));
                wordBean.setVar6_11(String.valueOf(monthMeteoCloud.getMemoryDistributed()));
                wordBean.setVar6_12(monthMeteoCloud.getMemoryDistributedRatio());
                wordBean.setVar6_13(String.valueOf(monthMeteoCloud.getLocalStorageTotal()));
                wordBean.setVar6_14(String.valueOf(monthMeteoCloud.getLocalStorageDistributed()));
                wordBean.setVar6_15(monthMeteoCloud.getLocalStorageDistributeRatio());
                wordBean.setVar6_16(String.valueOf(monthMeteoCloud.getNetStorageTotal()));
                wordBean.setVar6_17(String.valueOf(monthMeteoCloud.getNetStorageDistributed()));
                wordBean.setVar6_18(monthMeteoCloud.getNetStorageDistributeRatio());
            }

        }


        // 7.1 本月通信网络总体运行情况
        if (map.get("MONTH_COMMUNICATION_NET_TOTAL_RUNNING") == null) {
            wordBean.setVar7_1("0");
            wordBean.setVar7_2("0");
            wordBean.setVar7_3("0");
            wordBean.setVar7_4("0");
            wordBean.setVar7_5("0");
            wordBean.setVar7_6("/");
            wordBean.setVar7_7("/");
            wordBean.setVar7_8("/");
            wordBean.setVar7_9("/");
            wordBean.setVar7_10("/");
            wordBean.setVar7_11("/");
            wordBean.setVar7_12("/");
            wordBean.setVar7_13("/");
            wordBean.setVar7_14("/");
            wordBean.setVar7_15("/");
        } else {
            MonthCommunicationNet monthCommunicationNet = JSONUtil.toBean(map.get("MONTH_COMMUNICATION_NET_TOTAL_RUNNING").toString(), MonthCommunicationNet.class);
            if (monthCommunicationNet == null) {
                wordBean.setVar7_1("0");
                wordBean.setVar7_2("0");
                wordBean.setVar7_3("0");
                wordBean.setVar7_4("0");
                wordBean.setVar7_5("0");
                wordBean.setVar7_6("/");
                wordBean.setVar7_7("/");
                wordBean.setVar7_8("/");
                wordBean.setVar7_9("/");
                wordBean.setVar7_10("/");
                wordBean.setVar7_11("/");
                wordBean.setVar7_12("/");
                wordBean.setVar7_13("/");
                wordBean.setVar7_14("/");
                wordBean.setVar7_15("/");
            } else {
                wordBean.setVar7_1(monthCommunicationNet.getIntranetNetAreaFailureCount());
                wordBean.setVar7_2(monthCommunicationNet.getIntranetExternalLineFailureCount());
                wordBean.setVar7_3(monthCommunicationNet.getExtranetNetAreaFailureCount());
                wordBean.setVar7_4(monthCommunicationNet.getExtranetExternalLineFailureCount());
                wordBean.setVar7_5(monthCommunicationNet.getSafetyEventFailureCount());

                wordBean.setVar7_6(monthCommunicationNet.getIntranetNetAreaDealStatus());
                wordBean.setVar7_7(monthCommunicationNet.getIntranetExternalLineDealStatus());
                wordBean.setVar7_8(monthCommunicationNet.getExtranetNetAreaDealStatus());
                wordBean.setVar7_9(monthCommunicationNet.getExtranetExternalLineDealStatus());
                wordBean.setVar7_10(monthCommunicationNet.getSafetyEventDealStatus());

                wordBean.setVar7_11(monthCommunicationNet.getIntranetNetAreaRecoverStatus());
                wordBean.setVar7_12(monthCommunicationNet.getIntranetExternalLineRecoverStatus());
                wordBean.setVar7_13(monthCommunicationNet.getExtranetNetAreaRecoverStatus());
                wordBean.setVar7_14(monthCommunicationNet.getExtranetExternalLineRecoverStatus());
                wordBean.setVar7_15(monthCommunicationNet.getSafetyEventRecoverStatus());
            }
        }



        // 8.1 本月“天镜”与业务系统对接情况
        Object o1 = map.get("MONTH_TIANJING_AND_BUSINESS_SYSTEM");
        if (o1 != null) {
            List<MonthTianjingJoin> monthTianjingJoinList = JSONUtil.toList(o1.toString(), MonthTianjingJoin.class);
            for (int i = 0; i < monthTianjingJoinList.size(); i++) {
                monthTianjingJoinList.get(i).setOrder(i+1);
            }
            wordBean.setTable2_1(monthTianjingJoinList);
        }

        // 本月“天擎”新增气象数据产品接入情况
        Object o2 = map.get("MONTH_TIANQING_ADD_METEO_DATA_PRODUCT");
        List<MonthTianqingProduct> monthTianqingProductList = new ArrayList<>();
        if (o2 != null) {
            monthTianqingProductList = JSONUtil.toList(o2.toString(), MonthTianqingProduct.class);
            for (int i = 0; i < monthTianqingProductList.size(); i++) {
                monthTianqingProductList.get(i).setOrder(i+1);
            }
            wordBean.setTable3_1(monthTianqingProductList);
        }

        //本月“天擎”服务接口数据资源使用情况
        Object o3 = map.get("MONTH_TIANQING_SERVICE_INTERFACE_DATA_RESOURCE");
        List<DataResourceUse> dataResourceUseList = new ArrayList<>();
        if (o3 != null) {
            dataResourceUseList = JSONUtil.toList(o3.toString(), DataResourceUse.class);
            for (int i = 0; i < dataResourceUseList.size(); i++) {
                dataResourceUseList.get(i).setOrder(String.valueOf(i+1));
            }
            dataResourceUseList.get(dataResourceUseList.size() - 1).setOrder("合计");
            wordBean.setTable3_2(dataResourceUseList);
        }

        // 各单位业务系统及算法融入省级“天擎”情况总览
        Object o4 = map.get("UNIT_BUSINESS_SYSTEM_AND_ALGORITHM_IN_TIANQING");
        if (o4 != null) {
            List<BusinessSystemNumberVO> businessSystemNumberVOList = JSONUtil.toList(o4.toString(), BusinessSystemNumberVO.class);
            wordBean.setTable4_1(businessSystemNumberVOList);
        }

        // 本月省级“天擎”新增算法情况
        Object o5 = map.get("MONTH_PROVINCE_TIANQING_ADD_ALGORITHM");
        List<BusinessSystemStatistic> businessSystemStatisticList1 = new ArrayList<>();
        if (o5 != null) {
            businessSystemStatisticList1 = JSONUtil.toList(o5.toString(), BusinessSystemStatistic.class);
            for (int i = 0; i < businessSystemStatisticList1.size(); i++) {
                businessSystemStatisticList1.get(i).setOrder(i+1);
            }
            wordBean.setTable4_2(businessSystemStatisticList1);
        }

        // 本月省级“天擎”新增产品情况
        Object o6 = map.get("MONTH_PROVINCE_TIANQING_ADD_PRODUCT");
        List<BusinessSystemStatistic> businessSystemStatisticList2 = new ArrayList<>();
        if (o6 != null) {
            businessSystemStatisticList2 = JSONUtil.toList(o6.toString(), BusinessSystemStatistic.class);
            for (int i = 0; i < businessSystemStatisticList2.size(); i++) {
                businessSystemStatisticList2.get(i).setOrder(i+1);
            }
            wordBean.setTable4_3(businessSystemStatisticList2);
        }

        // 本月“天擎”接口访问次数排行
        Object o7 = map.get("MONTH_TIANQING_INTERFACE_QUERY_TIMES_RANK");
        if (o7 != null) {
            List<TianqingQueryTimes> tianqingQueryTimesList = JSONUtil.toList(o7.toString(), TianqingQueryTimes.class);
            for (int i = 0; i < tianqingQueryTimesList.size(); i++) {
                tianqingQueryTimesList.get(i).setOrder(i+1);
            }
            wordBean.setTable5_1(tianqingQueryTimesList);
        }

        // 本月“天擎”接口访问数据量排行
        Object o8 = map.get("MONTH_TIANQING_INTERFACE_QUERY_DATA_SIZE_RANK");
        if (o8 != null) {
            List<TianqingAccessDataSize> tianqingAccessDataSizeList = JSONUtil.toList(o8.toString(), TianqingAccessDataSize.class);
            for (int i = 0; i < tianqingAccessDataSizeList.size(); i++) {
                tianqingAccessDataSizeList.get(i).setOrder(i+1);
            }
            wordBean.setTable5_2(tianqingAccessDataSizeList);
        }

        // 本月各单位虚拟机分配及使用情况
        Object o9 = map.get("MONTH_UNIT_VM_DISTRIBUTION_AND_USAGE");
        if (o9 != null) {
            List<MonthVirtualMachine> monthVirtualMachineList = JSONUtil.toList(o9.toString(), MonthVirtualMachine.class);
            wordBean.setTable6_1(monthVirtualMachineList);
        }

        // 本月“天镜”运行情况统计
        Object o10 = map.get("MONTH_TIANJING_RUNNING_STATISTIC");
        List<MonthTianjingRunning> monthTianjingRunningList = new ArrayList<>();
        if (o10 != null) {
            monthTianjingRunningList = JSONUtil.toList(o10.toString(), MonthTianjingRunning.class);
            for (int i = 0; i < monthTianjingRunningList.size(); i++) {
                monthTianjingRunningList.get(i).setOrder(i+1);
            }
            wordBean.setTable8_1(monthTianjingRunningList);
        }

        // 本月业务系统运行情况统计
        Object o11 = map.get("MONTH_BUSINESS_SYSTEM_RUNNING_STATISTIC");
        List<MonthBusinessSystemRunning> monthBusinessSystemRunningList = new ArrayList<>();
        if (o11 != null) {
            monthBusinessSystemRunningList = JSONUtil.toList(o11.toString(), MonthBusinessSystemRunning.class);
            wordBean.setTable9_1(monthBusinessSystemRunningList);
        }

        // 业务运行情况综述
        wordBean.setVar1_1(yearStr);
        wordBean.setVar1_2(monthStr);
        wordBean.setVar1_3(wordBean.getVar2_1());
        wordBean.setVar1_4(wordBean.getVar2_2());
        wordBean.setVar1_5(wordBean.getVar6_5());
        wordBean.setVar1_6(wordBean.getVar6_8());
        wordBean.setVar1_7(wordBean.getVar6_11());
        wordBean.setVar1_8(wordBean.getVar6_14());
        wordBean.setVar1_9(String.valueOf(monthTianqingProductList.size()));
        wordBean.setVar1_10(wordBean.getVar3_7());
        wordBean.setVar1_11(String.valueOf(businessSystemStatisticList1.size()));
        wordBean.setVar1_12(String.valueOf(businessSystemStatisticList2.size()));
        int failureCount = Integer.parseInt(wordBean.getVar7_1()) + Integer.parseInt(wordBean.getVar7_2())+ Integer.parseInt(wordBean.getVar7_3())+ Integer.parseInt(wordBean.getVar7_4())+ Integer.parseInt(wordBean.getVar7_5());
        wordBean.setVar1_13(String.valueOf(failureCount));
        wordBean.setVar1_14("0");
        for (MonthBusinessSystemRunning monthBusinessSystemRunning : monthBusinessSystemRunningList) {
            if (monthBusinessSystemRunning.getBusinessSystemName().equals("总计")) {
                wordBean.setVar1_14(monthBusinessSystemRunning.getSeriousAlarmTotal());
                break;
            }
        }

        wordBean.setVar1_15(String.valueOf(monthTianjingRunningList.size()));


        // 读取word文档模板
        InputStream fileStream;
        try {
            fileStream = getResourceTemplatePath("data/monthReportTemplate.docx");
            if (fileStream == null) {
                throw new FileNotFoundException("模板文件不存在！");
            }
            DocxResolver docxResolver = new DocxResolver(new ExpressionResolver(wordBean));
            XWPFDocument document = new XWPFDocument(fileStream);
            docxResolver.resolve(document);
            List<XWPFTable> tables = document.getTables();
            // 本月“天擎”服务接口数据资源使用情况表，也就是第4张表需要合并最后一行
            XWPFTable xwpfTable4 = tables.get(4);
            if (!CollectionUtils.isEmpty(dataResourceUseList)) {
                TableMergeUtil.mergeCellsHorizontal(xwpfTable4, dataResourceUseList.size(), 0, 1);
            }

            // 浏览器导出文件
            String fileName = "GX“天镜”业务简报-月报（" + yearStr + "年" + monthStr + "月）";
            ExportUtil.exportDoc(response, document, fileName);
            document.close();
            fileStream.close();
        } catch (XmlException | IOException | InvalidFormatException e) {
            e.printStackTrace();
        }

    }

    public InputStream getResourceTemplatePath(String path) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(path);
        return classPathResource.getInputStream();
    }
}
